<template>
  <div class="app-container">

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          :disabled="!orderInfo.no"
          @click="handleAdd"
          v-hasPermi="['quality:productQualityItem:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['quality:productQualityItem:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['quality:productQualityItem:remove']"
        >删除</el-button>
      </el-col>

    </el-row>

    <el-table height="25vh" v-loading="loading" :data="detailList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <af-table-column label="质检项名称" align="center" prop="itemName" />
      <el-table-column label="值类型" align="center" prop="valueType" >
        <template slot-scope="scope">
          <dict-tag :options="valueTypeList" :value="scope.row.valueType"/>
        </template>
      </el-table-column>
      <el-table-column label="标准下限" align="center" prop="lowerLimitValue" />
      <el-table-column label="标准上限" align="center" prop="upperLimitValue" />
      <af-table-column label="方法" align="center" prop="method" />
      <af-table-column label="质检类型" align="center" prop="qualityType" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.quality_type" :value="scope.row.qualityType"/>
        </template>
      </af-table-column>
    </el-table>


    <!-- 添加或修改单据明细对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="质检项" prop="itemNo">
          <el-select @change="changeQualityItem" style="width:100%;" v-model="form.itemNo" filterable placeholder="请选择质检项">
            <el-option
              v-for="dict in qualityItemList"
              :key="dict.no"
              :label="dict.name"
              :value="dict.no"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="值类型" prop="valueType">
          <el-select disabled v-model="form.valueType" style="width:100%;" placeholder="值类型" >
            <el-option
              v-for="item in valueTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="标准下限" v-if="form.valueType == 'RANGE'"  prop="lowerLimitValue">
          <el-input v-model.trim="form.lowerLimitValue" placeholder="请输入标准下限" />
        </el-form-item>

        <el-form-item label="标准上限" v-if="form.valueType == 'RANGE'" prop="upperLimitValue">
          <el-input v-model.trim="form.upperLimitValue" placeholder="请输入标准上限" />
        </el-form-item>

        <el-form-item label="方法" prop="method">
          <el-input v-model.trim="form.method" placeholder="请输入方法" />
        </el-form-item>

        <el-form-item label="质检类型" prop="qualityType">
          <el-select multiple v-model="form.qualityType" style="width:100%;" placeholder="质检类型" >
            <el-option
              v-for="dict in dict.type.quality_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listQualityItem,listQualityItemDetail, getQualityItemDetail, delQualityItemDetail, addQualityItemDetail, updateQualityItemDetail } from "./api/quelityItemDetail";
import { isEmpty, isQualityFour} from '@/utils/validate';
export default {
  name: "salesOrderDetail",
  dicts: ['basic_product_type', 'quality_type'],
  props:{
    orderData:{}
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 已选择的质检项
      notInNos: [],
      productNos: [],
      pitchOnTotalOrderQty: 0,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 单据明细表格数据
      detailList: [],
      // 质检项列表
      qualityItemList: [],
      valueTypeList:[
        {
          id:0,
          label:'范围值',
          value:'RANGE'
        },
        {
          id:1,
          label:'状态值',
          value:'STATUS'
        },
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 99999,
        no: null,
        batchNo: null,
        productNo: null,
        storehouseLocationNo: null,
        picker: null,
        orderDetailStatus: null,
        createUser: null,
        updateUser: null,
        sort: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        itemNo: [
          { required: true, message: "质检项不能为空", trigger: "change" }
        ],
        upperLimitValue: [
          { required: true, message: "标准上限不能为空", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              if ((isEmpty(value) || isQualityFour(value))) {
                callback();
              } else {
                callback('请输入数值，保留4位小数');
              }
            },
            trigger: "blur",
          },
        ],
        lowerLimitValue: [
          { required: true, message: "标准下限不能为空", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              if ((isEmpty(value) || isQualityFour(value))) {
                callback();
              } else {
                callback('请输入数值，保留4位小数');
              }
            },
            trigger: "blur",
          },
        ],
        qualityType: [{ required: true, message: "质检类型不能为空", trigger: "change" }]
      },
      // 订单信息
      orderInfo:{
        no : null
      }
    };
  },
  created() {
    this.getList();
  },
  watch: {
    // 监视订单信息变动
    orderData(newValue){
      if(!newValue || !newValue.no){
        this.orderInfo = {no : null};
      }else {
        this.orderInfo = newValue;
      }
      this.getList();
    }
  },
  methods: {
    /** 获取质检项列表 */
    getListQuality(){
      listQualityItem({
        pageNum:1,
        pageSize:99999,
        notInNos:this.notInNos
      }).then(response => {
        this.qualityItemList = response.rows;
      });
    },
    // 修改物料
    changeQualityItem(){
      const qualityItem = this.qualityItemList.find(item => item.no === this.form.itemNo)
      this.$set(this.form,'itemName',qualityItem.name);
      this.$set(this.form,'valueType',qualityItem.valueType);
      this.$set(this.form,'upperLimitValue',qualityItem.upperLimitValue);
      this.$set(this.form,'lowerLimitValue',qualityItem.lowerLimitValue);
      this.$set(this.form,'method',qualityItem.method);
    },
    /** 查询单据明细列表 */
    getList() {
      this.loading = true;
      this.queryParams.productNo = this.orderInfo.productNo;
      if(!this.queryParams.productNo){
        this.detailList = [];
        this.total = 0;
        this.loading = false;
        return;
      }

      listQualityItemDetail(this.queryParams).then(response => {
        this.detailList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$set(this,'queryParams',{});
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.itemNos = selection.map(item => item.itemNo)
      this.pitchOnTotalOrderQty = 0;
      selection.forEach(item => this.pitchOnTotalOrderQty = this.pitchOnTotalOrderQty + item.orderQty);
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.productNo = this.orderInfo.productNo;
      this.open = true;
      // 过滤已存在的质检项
      this.detailList.forEach((row) => {
        this.notInNos.push(row.itemNo);
      });
      // 重新获取物料列表
      this.getListQuality();
      this.title = "添加质检项";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      // 过滤BOM主表的物料以及明细已有的物料
      this.$set(this,'notInNos',[]);
      this.detailList.forEach((row) => {
        if (row.itemNo != this.itemNos[0]) {
          this.notInNos.push(row.itemNo);
        }
      });

      // 重新获取物料列表
      this.getListQuality();
      const id = row.id || this.ids
      getQualityItemDetail(id).then(response => {
        console.log(response.data.qualityType.split(','))
        this.form = {...response.data, qualityType:response.data.qualityType?response.data.qualityType.split(','):[]};
        this.open = true;
        this.title = "修改质检项明细";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.lowerLimitValue && this.form.upperLimitValue) {
            if (this.form.lowerLimitValue > this.form.upperLimitValue) {
              this.$modal.msgWarning("标准上限不能小于标准下限");
              return;
            }
          }
          let form = {...this.form, qualityType: this.form.qualityType.join(',')}
          if (this.form.id != null) {
            updateQualityItemDetail(form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addQualityItemDetail(form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm(this.$t('deleteTip', { num: ids.length })).then(function() {
        return delQualityItemDetail(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  }
};
</script>
